﻿/* 
 * author: www.cnblogs.com/luminji
 * date  : 2011/12/28
 */
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using Luminji.Infrastructure.UnitOfWork;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Luminji.Exam.Model.Subjects
{

    public class SubjectService 
    {
        ISubjectRepository _subjectRepository;
        IUnitOfWork _unitOfWork;

        private static IList<Subject> _all;
        private static IList<Subject> _tree;

        public SubjectService(ISubjectRepository subjectRepository, IUnitOfWork unitOfWork)
        {
            _subjectRepository = subjectRepository;
            _unitOfWork = unitOfWork;
        }

        public IList<Subject> FindAllIntoThree()
        {
            if (_tree == null)
            {
                _all = _subjectRepository.Find();
                Subject root = new Subject();
                RecusiveSubject(root, null);
                _tree = root.Children;
            }
            return _tree;
        }

        void RecusiveSubject(Subject subject, string parentCode)
        {
            var tempList = from p in _all where p.ParentCode == parentCode select p;
            if (tempList.Count() == 0)
            {
                return;
            }
            else
            {
                subject.Children = tempList.ToList();
                foreach (var item in tempList)
                {
                    RecusiveSubject(item, item.SubjectCode);
                }
            }
        }
    }
}
